package net.hn.hnms.biz.plan.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import net.hn.hnms.biz.plan.domain.DimShift;
import net.hn.hnms.biz.plan.domain.ExecutionOther;
import net.hn.hnms.biz.plan.mapper.DimShiftMapper;
import net.hn.hnms.biz.plan.mapper.ExecutionOtherMapper;
import net.hn.hnms.biz.plan.request.ExecutionOtherReq;
import net.hn.hnms.biz.plan.service.IExecutionOtherService;
import net.hn.hnms.biz.plan.vo.ExecutionOtherVO;
import net.hn.hnms.sys.common.core.constant.Constants;
import net.hn.hnms.sys.common.core.domain.ResponsePage;
import net.hn.hnms.sys.common.core.exception.HuaNengException;
import net.hn.hnms.sys.common.mybatis.core.page.PageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author zhaoyang
 * 其他生产计划管理服务层实现
 * @date 2022-08-01
 */

@Service
@DS("master")
public class ExecutionOtherServiceImpl extends BaseService<ExecutionOther, ExecutionOtherVO> implements IExecutionOtherService {

    @Autowired
    private ExecutionOtherMapper executionOtherMapper;

    @Autowired
    private DimShiftMapper dimShiftMapper;

    /**
     * @param executionOther
     * @param pageQuery       查询其他生产计划列表
     */
    @Override
    public ResponsePage<ExecutionOtherVO> selectPageList(ExecutionOtherReq executionOther, PageQuery pageQuery) {

        Page<ExecutionOther> page = executionOtherMapper.selectPage(pageQuery.build(), buildQuery(executionOther).orderByDesc(ExecutionOther::getExecutionDate).orderByDesc(ExecutionOther::getCreateTime));
        List<ExecutionOtherVO> list = page.getRecords().stream().map(o -> convertWithUser(o, ExecutionOtherVO.class)).collect(Collectors.toList());
        if (CollUtil.isNotEmpty(list)) {
            DynamicDataSourceContextHolder.push("slave");
            Map<String, String> map = dimShiftMapper.selectList(new LambdaQueryWrapper<DimShift>().eq(StrUtil.isNotBlank(executionOther.getMineCode()), DimShift::getMineCode, executionOther.getMineCode()))
                    .stream().collect(Collectors.toMap(DimShift::getShiftId, DimShift::getShiftName));
            DynamicDataSourceContextHolder.clear();

            for (ExecutionOtherVO executionOtherVO : list) {
                executionOtherVO.setShiftName(map.get(executionOtherVO.getShiftId()));
            }
        }
        return new ResponsePage<>(list, page.getTotal());
    }


    /**
     * 构造查询条件
     * @param req
     * @return LambdaQueryWrapper<ExecutionOther> 查询条件
     */
    private LambdaQueryWrapper<ExecutionOther> buildQuery(ExecutionOtherReq req){
        LambdaQueryWrapper<ExecutionOther> lqw = new LambdaQueryWrapper<ExecutionOther>()
                .ge(req.getBeginDateTime() != null, ExecutionOther::getExecutionDate, req.getBeginDateTime())
                .le(req.getEndDateTime() != null, ExecutionOther::getExecutionDate, req.getEndDateTime())
                .eq(StrUtil.isNotBlank(req.getShiftId()), ExecutionOther::getShiftId, req.getShiftId())
                .and(o->o.eq(req.getMineCode()!=null, ExecutionOther::getMineCode, req.getMineCode()).or().eq(req.getCompanyCode()!=null, ExecutionOther::getCompanyCode, req.getCompanyCode()));

//                .eq(StrUtil.isNotBlank(req.getMineCode()), ExecutionOther::getMineCode, req.getMineCode());
        return lqw;
    }

    /**
     *
     * @param executionOther
     * 查询带值班人员列表
     */
    @Override
    public List<ExecutionOtherVO> selectList(ExecutionOtherReq executionOther) {
        List<ExecutionOther> list = executionOtherMapper.selectList(buildQuery(executionOther));
        return list.stream().map(o -> convert(o, ExecutionOtherVO.class)).collect(Collectors.toList());
    }

    /**
     * @param executionOther 新增其他生产计划
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insert(ExecutionOtherReq executionOther) {
//        QueryWrapper<ExecutionOther> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("development_plan_code", executionOther.getExecutionOtherCode());
//        if (executionOtherMapper.selectCount(queryWrapper) > 0) {
//            throw new HuaNengException(Constants.FAIL, "已存在相同的计划编号");
//        }
        ExecutionOther insertObj = new ExecutionOther();
        BeanUtil.copyProperties(executionOther, insertObj);
        return executionOtherMapper.insert(insertObj);
    }

    /**
     * @param idList 批量删除 id集合
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<String> idList) {
        executionOtherMapper.deleteBatchIds(idList);
    }

    /**
     * @param executionOther 单个修改 按照主键修改信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateById(ExecutionOtherReq executionOther) {
        if (StrUtil.isBlank(executionOther.getOtherImplementId())) {
            throw new HuaNengException(Constants.FAIL, "id不能为空");
        }

        ExecutionOther updateObj = new ExecutionOther();
        BeanUtil.copyProperties(executionOther, updateObj);
        int updateCount = executionOtherMapper.updateById(updateObj);
        if (updateCount == 0) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
    }

    /**
     * @param id 按主键id查询详情
     */
    @Override
    public ExecutionOtherVO selectDetailById(String id) {
        ExecutionOther executionOther = executionOtherMapper.selectById(id);
        if (executionOther == null) {
            throw new HuaNengException(Constants.FAIL, "数据不存在");
        }
        return convertWithUser(executionOther, ExecutionOtherVO.class);
    }
}
